﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThresholdAssistant.Autofac;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.NLogSdk;
using ThresholdAssistant.Tools;
using ThresholdAssistant.WebAPI.Models;
using ThresholdAssistant.WebAPI.Models.Result.Data;
using ThresholdAssistant.WebAPI.Repository;

namespace ThresholdAssistant.WebAPI.Service
{
    /// <summary>
    /// 数据服务
    /// </summary>
    public class RecordService : BaseService, IBaseAutofac
    {
        /// <summary>
        /// 数据仓储
        /// </summary>
        public RecordRepository RecordRepository { get; set; }
        /// <summary>
        /// 数组仓储
        /// </summary>
        public SiteRepository SiteRepository { get; set; }
        /// <summary>
        /// 阈值服务
        /// </summary>
        public ThresholdService ThresholdService { get; set; }
        /// <summary>
        /// 阈值仓储
        /// </summary>
        public ThresholdRepository ThresholdRepository { get; set; }
        /// <summary>
        /// 用户仓储
        /// </summary>
        public MemberRepository MemberRepository { get; set; }
        /// <summary>
        /// 标签仓储
        /// </summary>
        public TagRepository TagRepository { get; set; }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<ContractResult<IEnumerable<object>>> GetListAsync(GetRecordListParam param)
        {
            var result = new ContractResult<IEnumerable<object>>();

            //数据组
            var sites = await SiteRepository.GetListAsync(param.GroupId);
            if (sites == null || sites.Any() == false)
            {
                return result;
            }

            //数据
            var records = await RecordRepository.GetListAsync(param);

            //阈值
            var thresholds = new List<ThresholdData>();
            if (param.Type == 1 || param.Type == 2)
            {
                var thresholdRes = await ThresholdService.GetListAsync(new GetThresholdListParam() { GroupId = param.GroupId });
                if (thresholdRes.Data.IsNotNull() && thresholdRes.Data.Any())
                {
                    thresholds = thresholdRes.Data.ToList();
                }
            }

            var list = new List<object>();
            var index = 0;
            var _records = new List<RecordData>();
            switch (param.Type)
            {
                case 0:
                    //标签列表
                    foreach (var site in sites)
                    {
                        index = 0;
                        _records = records.Where(x => x.SiteId == site.Id).ToList();
                        _records = _records.OrderByDescending(x => x.UpdateTime).ToList();
                        _records.ForEach(x => { x.rowIndex = 110 + ((++index - 1) * 90); x.UpdateTimeStr = x.UpdateTime.ToString("HH:mm"); });
                        list.Add(new
                        {
                            site_id = site.Id,
                            site_name = site.Name,
                            records = _records
                        });
                    }
                    break;
                case 1:
                    //标签统计               
                    foreach (var site in sites)
                    {
                        index = 0;
                        _records = records.Where(x => x.SiteId == site.Id).ToList();

                        var query = from item in _records
                                    group item by new
                                    {
                                        item.TagId,
                                        item.TagName,
                                        item.TagTypeName
                                    } into g
                                    select new RecordData
                                    {
                                        TagId = g.Key.TagId,
                                        TagName = g.Key.TagName,
                                        TagTypeName = g.Key.TagTypeName,
                                        DataValue = g.Sum(p => p.DataValue),
                                    };
                        _records = query.OrderBy(x => x.TagId).ToList();
                        _records.ForEach(x => { x.rowIndex = 110 + ((++index - 1) * 90); x.UpdateTimeStr = x.UpdateTime.ToString("HH:mm"); x.WarnClass = GetWarnClass(thresholds, x.DataValue); });
                        list.Add(new
                        {
                            site_id = site.Id,
                            site_name = site.Name,
                            records = _records
                        });
                    }
                    break;
                case 2:
                    //标签类型统计
                    foreach (var site in sites)
                    {
                        index = 0;
                        _records = records.Where(x => x.SiteId == site.Id).ToList();

                        var query = from item in _records
                                    group item by new
                                    {
                                        item.TagId,
                                        item.TagName,
                                        item.TagTypeName
                                    } into g
                                    select new RecordData
                                    {
                                        TagId = g.Key.TagId,
                                        TagName = g.Key.TagName,
                                        TagTypeName = g.Key.TagTypeName,
                                        DataValue = g.Sum(p => p.DataValue),
                                    };
                        _records = query.OrderBy(x => x.TagTypeName).OrderBy(x => x.TagId).ToList();
                        _records.ForEach(x => { x.rowIndex = 110 + ((++index - 1) * 90); x.UpdateTimeStr = x.UpdateTime.ToString("HH:mm"); x.WarnClass = GetWarnClass(thresholds, x.DataValue); });
                        list.Add(new
                        {
                            site_id = site.Id,
                            site_name = site.Name,
                            records = _records
                        });
                    }
                    break;
            }

            result.Data = list;
            return result.SetSuceccful();
        }
        private string GetWarnClass(List<ThresholdData> thresholds, double DataValue)
        {
            if (thresholds.IsNull() || thresholds.Any() == false)
            {
                return "";
            }

            foreach (var threshold in thresholds)
            {
                if (DataValue >= threshold.StartValue && DataValue <= threshold.EndValue)
                {
                    return "red";
                }
            }
            return "";
        }

        /// <summary>
        /// 汇总
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<ContractResult<IEnumerable<VRecordData>>> GetVListAsync(GetRecordListParam param)
        {
            var result = new ContractResult<IEnumerable<VRecordData>>();
            var list = await RecordRepository.GetVListAsync(param.GroupId);
            result.Data = (IEnumerable<VRecordData>)list;
            return result.SetSuceccful();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<ContractResult<long>> AddAsync(AddRecordParam param)
        {
            var result = new ContractResult<long>();
            var id = await RecordRepository.AddAsync(new Record
            {
                GroupId = param.GroupId,
                SiteId = param.SiteId,
                TagId = param.TagId,
                DataValue = param.DataValue,
                CreateId = param.MemberId,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                Remark = ""
            });

            return result.SetSuceccful(id);
        }
        public async Task<SmsInfoParam> CheckThreshold(AddRecordParam param)
        {
            var result = new SmsInfoParam();
            if (param.GroupId == 0)
            {
                return result;
            }
            if (param.SiteId == 0)
            {
                return result;
            }
            if (param.TagId == 0)
            {
                return result;
            }

            //数据
            var records = await RecordRepository.GetListAsync(new GetRecordListParam() { GroupId = param.GroupId, SiteId = param.SiteId, TagIds = new List<long>() { param.TagId } });
            if (records == null || records.Any() == false)
            {
                return result;
            }
            var sumDataValue = records.Sum(x => x.DataValue);

            //阈值校验
            var thresholds = await ThresholdRepository.GetListByGroupIdAsync(param.GroupId);
            if (thresholds == null || thresholds.Any() == false)
            {
                return result;
            }
            var isExists = false;
            foreach (var item in thresholds)
            {
                if (sumDataValue >= item.StartValue && sumDataValue <= item.EndValue)
                {
                    isExists = true;
                    break;
                }
            }
            if (isExists == false)
            {
                return result;
            }

            //会员
            var member = await MemberRepository.GetInfoAsync(param.GroupId);
            if (member == null)
            {
                return result;
            }

            if (string.IsNullOrWhiteSpace(member.Phone))
            {
                NLogUtil.Warn($"{param.GroupId}组成员{member.Id}手机号码为空，无法发送短信");
                return result;
            }

            //标签
            var tag = await TagRepository.GetInfoAsync(param.TagId);
            if (tag == null)
            {
                return result;
            }
            //分组
            var site = await SiteRepository.GetInfoAsync(param.SiteId);
            if (site == null)
            {
                return result;
            }
            //内容
            var content = $"{tag?.Name}({site?.Name})";
            var SmsInfo = ThresholdFileService.ReadSms(param.GroupId.ToString());
            if (SmsInfo != null && string.IsNullOrEmpty(SmsInfo.Title) == false && SmsInfo.Title.Contains(content) == false)
            {
                content = content + "等多条";
            }

            result = new SmsInfoParam()
            {
                GroupId = param.GroupId.ToString(),
                DateTime = DateTime.Now,
                Name = member?.NickName,
                Phone = member?.Phone,
                Title = content,
                Value = sumDataValue,
            };
            ThresholdFileService.CreateSms(result);
            return result;
        }

        /// <summary>
        /// 单个
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<ContractResult<RecordData>> GetInfoAsync(long id)
        {
            var result = new ContractResult<RecordData>();
            result.Data = await RecordRepository.GetInfoAsync(id);
            return result.SetSuceccful();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<ContractResult> UpdateAsync(UpdateRecordParam param)
        {
            var result = new ContractResult();
            var recordInfo = await RecordRepository.GetInfoAsync(param.Id);
            if (recordInfo != null)
            {
                recordInfo.Id = param.Id;
                recordInfo.DataValue = param.DataValue;
                await RecordRepository.UpdateValueAsync(recordInfo);
            }
            return result.SetSuceccful();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ContractResult> DeleteAsync(long id)
        {
            var result = new ContractResult();
            //仓储职责规范
            await RecordRepository.DeleteAsync(id);
            return result.SetSuceccful();
        }

    }
}
